<?php
/**
 * Created by PhpStorm.
 * User: Liu
 * Date: 2022/5/13
 * Time: 10:31
 */

namespace app\index\controller;

use app\admin\common\Base;
use app\index\Common;

class Product extends Common {
    public function index(){

        $this->seoContent(2);
        return $this->fetch();
    }

    public function details($id){
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $where[] = ['id|seo_link','=',$id];
        $info = db('product')->where($where)->find();
        if (!$info){
            //抛出异常
            abort(404, '');
        }
        $info['carousel'] = json_decode($info['carousel'],true);
        /*$relation = !empty($info['related_products']) ? $this->getRelatedProduct($info['related_products']) : [];
        $this->assign('relation_list',$relation);*/
        $this->assign('seo_title',$info['seo_title']);
        $this->assign('seo_keywords',$info['seo_keywords']);
        $this->assign('seo_describe',$info['seo_describe']);
        $this->assign('info',$info);
        return $this->fetch();
    }

    //获取所有子级
    function getAllChild($pid,$table){
        $data = db($table)->field('id')->where('pid',$pid)->select();
        $child_ids = [];
        foreach ($data as $v){
            $child_ids[] = $v['id'];
            $child_ids = array_merge($child_ids, $this->getAllChild($v['id'],$table));
        }
        return $child_ids;
    }

    /**
     * 获取关联产品
     * @param string $ids 关联产品ID id1,id2,id3,...
     * @return mixed
     */
    public function getRelatedProduct($ids){
        $ids = array_filter(explode(',',$ids));
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $where[] = ['id','in',$ids];

        $list = db('product')
            ->where($where)
            ->field('id,name,cover,seo_link,seo_keywords')
            ->select();

        if (!empty($list)){
            foreach ($list as $k => $v){
                $list[$k]['link'] = handle_detail_link('product',$v['id'],$v['seo_link']);
            }
        }

        return $list;

    }
}